﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace KNXConnector.Settings
{
    public class SettingsReader : ISettingsReader
    {
        public List<KNXObjects.ObjectBase> GetAllObjects()
        {
            KNXFramework.KNXConnector.Settings.KNXObjects objects = LoadSettings();
            List<KNXObjects.ObjectBase> listOfObjects = new List<KNXObjects.ObjectBase>();
            objects.KNXObjectList.ForEach(x => listOfObjects.Add(KNXObjects.ObjectBase.GetConcreteObject(x.Id, x.GAD, x.Name, x.Type, x.Flags)));
            return listOfObjects;
        }
        private KNXFramework.KNXConnector.Settings.KNXObjects LoadSettings()
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(KNXFramework.KNXConnector.Settings.KNXObjects));
            KNXFramework.KNXConnector.Settings.KNXObjects objects;
            Uri fileUri = new Uri(ConfigFilePath);
            using (StreamReader sr = System.IO.File.OpenText(fileUri.LocalPath))
            {
                objects = xmlSerializer.Deserialize(sr) as KNXFramework.KNXConnector.Settings.KNXObjects;
            }
            return objects;
        }


        private string m_ConfigFilePath;
        public string ConfigFilePath
        {
            get
            {
                if (string.IsNullOrWhiteSpace(m_ConfigFilePath))
                {
                    string filePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
                    filePath += "\\Settings\\conf.xml";
                    m_ConfigFilePath = filePath;
                }
                return m_ConfigFilePath;

            }
            set
            {
                m_ConfigFilePath = value;
            }
        }

    }
}
